<?php
// ####################### SET PHP ENVIRONMENT ###########################
error_reporting(E_ALL & ~E_NOTICE);

// #################### DEFINE IMPORTANT CONSTANTS #######################

define('THIS_SCRIPT', 'teamspeak');
define('CSRF_PROTECTION', true);  

// ################### PRE-CACHE TEMPLATES AND DATA ######################
// get special phrase groups
$phrasegroups = array();

// get special data templates from the datastore
$specialtemplates = array();

// pre-cache templates used by all actions
$globaltemplates = array('neo_teamspeak', 'neo_ts_index', 'neo_ts_viewer', 'neo_ts_generate', 'neo_ts_setuid', 'neo_ts_setuid_bit');

// pre-cache templates used by specific actions
$actiontemplates = array();

// ######################### REQUIRE BACK-END ############################
require_once('./global.php');

// #######################################################################
// ######################## START MAIN SCRIPT ############################
// #######################################################################
if ($vbulletin->options['neots_enable_product'] AND isset($vbulletin->options['neots_uname'], $vbulletin->options['neots_pass'], $vbulletin->options['neots_ip'], $vbulletin->options['neots_port'], $vbulletin->options['neots_id'])) {
	/* load framework library */
	require_once("./teamspeak/TeamSpeak3.php");
	/* initialize */
	TeamSpeak3::init();
	/* set standard variables */
	$perms = cache_permissions($vbulletin->userinfo);
	$neots_border = 'style="border-top:1px;border-bottom:0px;border-left:0px;border-right:0px;border-color:'.vB_Template_Runtime::fetchStyleVar('shade_color').';border-style:dashed"';
	$ts3_VirtualServer = TeamSpeak3::factory("serverquery://".$vbulletin->options['neots_uname'].":".$vbulletin->options['neots_pass']."@".$vbulletin->options['neots_ip'].":".$vbulletin->options['neots_port']."/?server_port=".$vbulletin->options['neots_id']."#no_query_clients");
	/* use switch to find the right page */
	
	if (empty($_REQUEST['do'])) {
		$_REQUEST['do'] = 'index';
	}
	/* page viewer */
	if ($_REQUEST['do'] == 'viewer') {
		$navbit = 'Viewer';
		if ($vbulletin->check_user_permission('neots_perms', 'neots_viewer')) {
			try {
				$ts3_VirtualServer->setLoadClientlistFirst(TRUE);
				$pattern = "<div id='%0' class='%1 table'><div class='%2 tr'><div class='%3 td'>%4</div><div class='%5 td' title='%6'>%7 %8</div><div class='%9 td'>%10%11</div></div></div>\n";
				$htmlviewer = $ts3_VirtualServer->getViewer(new TeamSpeak3_Viewer_Html("./teamspeak/images/viewer/", "./teamspeak/images/flags/", "./teamspeak/ts3icon.php", $pattern));
				$templater = vB_Template::create('neo_ts_viewer');
				$templater->register('htmlviewer', $htmlviewer);
				$content = $templater->render(); 
			}
			catch(Exception $e) {
				$content .= fetch_error('neo_teamspeak_error', $e->getCode(), $e->getMessage());
			}
		}
		else {
			eval(standard_error(fetch_error('neots_noperm_error')));
		}
	}
	/* page add */
	if ($_REQUEST['do'] == 'create') {
		$navbit = 'Create Token';
		if ($vbulletin->check_user_permission('neots_perms', 'neots_generate')) { 
			$tokens = $vbulletin->userinfo['neots_token'];
			if ($tokens >= $perms['neots_tokenlimit']) {
				$content = construct_phrase($vbphrase['neots_tokenlimit'], $vbulletin->userinfo['username'], $tokens);
			}
			elseif ($tokens < $perms['neots_tokenlimit']) {
				try {
					$userdata =& datamanager_init('User', $vbulletin, ERRTYPE_ARRAY);
					$existing = array( 
						'userid' => $vbulletin->userinfo['userid'],
						'username' => $vbulletin->userinfo['username'],
					);
					$userdata->set_existing($existing);
					$userdata->set('neots_token', $tokens+1);
					$userdata->pre_save();
					if (!empty($userdata->errors)) { 
						$errorlist = ''; 
						foreach ($userdata->errors AS $index => $error) { 
							$errorlist .= "<li>$error</li>";
							break; 
						}
						eval(standard_error(fetch_error('neo_db_error', $errorlist)));
					}
					else {
						$customFieldSet = "ident=vbuser value=".$vbulletin->userinfo['username']."|ident=vbid value=".$vbulletin->userinfo['userid'];
						if($perms['neots_sgroup']) {
							$ugid = unserialize($perms['neots_sgroup']);
							$ugid = $ugid[0];
						}
						$token=$ts3_VirtualServer->privilegeKeyCreate(0,$ugid,0,"Auto Generated For ".$vbulletin->userinfo['username'],$customFieldSet);
						$ts_group = $ts3_VirtualServer->serverGroupGetById($ugid);
						$userdata->save();
						$templater = vB_Template::create('neo_ts_generate');
						$templater->register('username', $vbulletin->userinfo['username']);
						$templater->register('tokens', $tokens);
						$templater->register('tokenlimit', $perms['neots_tokenlimit']);
						$templater->register('token', $token);
						$templater->register('ts_group', $ts_group);
						$templater->register('ts_ip', $vbulletin->options['neots_ip']);
						$templater->register('ts_id', $vbulletin->options['neots_id']);
						$templater->register('ts_bookmark', $vbulletin->options['neots_bookmark']);
						$content = $templater->render();
					}
				}
				catch(Exception $e) {
					$content .= fetch_error('neo_teamspeak_error', $e->getCode(), $e->getMessage());
				}
			}
		}
		else {
			eval(standard_error(fetch_error('neots_noperm_error')));
		}
	}
	/* page reset */
	if ($_REQUEST['do'] == 'reset') {
		$navbit = 'Token Reset';
		if ($vbulletin->check_user_permission('neots_perms', 'neots_reset')) {
			$userdata =& datamanager_init('User', $vbulletin, ERRTYPE_ARRAY);
			$existing = array( 
				'userid' => $vbulletin->userinfo['userid'],
				'username' => $vbulletin->userinfo['username'],
			);
			$userdata->set_existing($existing);
			$userdata->set('neots_token', '0');
			$userdata->pre_save();
			if (!empty($userdata->errors)) { 
				$errorlist = ''; 
				foreach ($userdata->errors AS $index => $error) { 
					$errorlist .= "<li>$error</li>";
					break; 
				}
				eval(standard_error(fetch_error('neo_db_error', $errorlist)));
			}
			else {
				$userdata->save();
				$content = construct_phrase($vbphrase['neots_resetsuccess'], $vbulletin->userinfo['username']);
			}
		}
		else {
			eval(standard_error(fetch_error('neots_noperm_error')));
		}
	}
	/* Set UID for Teamspeak */
	if ($_REQUEST['do'] == 'setuid') {
		$navbit = 'Set UID';
		if (!($vbulletin->check_user_permission('neots_perms', 'neots_setuid'))) {
			eval(standard_error(fetch_error('neots_noperm_error')));
		}
		else {
			$vbulletin->userinfo['neots_uid'] = unserialize($vbulletin->userinfo['neots_uid']); 
			if(empty($vbulletin->userinfo['neots_uid'])) { 
				$vbulletin->userinfo['neots_uid'] = array(); 
				$N = $vbulletin->userinfo['permissions']['neots_tokenlimit']; 
				for($i=0; $i < $N; $i++) { 
					$templater = vB_Template::create('neo_ts_setuid_bit');
					$templater->register('i', $i);
					$templater->register('u', $i+1);
					$neo_ts_setuid_bit .= $templater->render();
				} 
			}  
			else { 
				$N = $vbulletin->userinfo['permissions']['neots_tokenlimit']; 
				for($i=0; $i < $N; $i++) { 
					$useruid = $vbulletin->userinfo['neots_uid'][$i];
					$templater = vB_Template::create('neo_ts_setuid_bit');
					$templater->register('useruid', $useruid);
					$templater->register('i', $i);
					$templater->register('u', $i+1);
					$neo_ts_setuid_bit .= $templater->render();
				} 
			}
		}
		$templater = vB_Template::create('neo_ts_setuid');
		$templater->register('neo_ts_setuid_bit', $neo_ts_setuid_bit);
		$content = $templater->render();
	}
	/* Perform Save of UID */
	if ($_REQUEST['do'] == 'dosetuid') {
		$navbit = 'Submit UID';
		if (!($vbulletin->check_user_permission('neots_perms', 'neots_setuid'))) {
			eval(standard_error(fetch_error('neots_noperm_error')));
		}
		else {
			$vbulletin->input->clean_array_gpc('p', array(
				'user'              => TYPE_NOCLEAN,
			));
			$vbulletin->userinfo['neots_uid'] = unserialize($vbulletin->userinfo['neots_uid']);
			if(is_array($vbulletin->userinfo['neots_uid'])) {
				foreach($vbulletin->userinfo['neots_uid'] as $key => $value) { 
					if($value == "") { 
						unset($vbulletin->userinfo['neots_uid'][$key]); 
					} 
				}
				$vbulletin->userinfo['neots_uid'] = array_unique($vbulletin->userinfo['neots_uid']);
				if(!(is_array($vbulletin->GPC['user']['neots_uid']))) {
					$vbulletin->GPC['user']['neots_uid'] = array_merge(array($vbulletin->GPC['user']['neots_uid']), $vbulletin->userinfo['neots_uid']);
					$vbulletin->GPC['user']['neots_uid'] = array_unique($vbulletin->GPC['user']['neots_uid']);
					sort($vbulletin->GPC['user']['neots_uid']);
				}
			}
			$vbulletin->userinfo['neots_uid'] = $vbulletin->GPC['user']['neots_uid'];
			$userdata =& datamanager_init('User', $vbulletin, ERRTYPE_ARRAY);
			$existing = array( 
				'userid' => $vbulletin->userinfo['userid'],
				'username' => $vbulletin->userinfo['username'],
				'usergroupid' => $vbulletin->userinfo['usergroupid'],
				'membergroupids' => $vbulletin->userinfo['membergroupids'],
			);
			$userdata->set_existing($existing);
			$userdata->set('neots_uid', $vbulletin->userinfo['neots_uid']);
			$userdata->pre_save();
			if (!empty($userdata->errors)) { 
				$errorlist = ''; 
				foreach ($userdata->errors AS $index => $error) { 
					$errorlist .= "<li>$error</li>";
					break; 
				}
				eval(standard_error(fetch_error('neo_db_error', $errorlist)));
			}
			else {
				$userdata->save();
				$content = "User UID saved correctly";
			}
		}
	}
	/* page test (my sandbox) */
	if ($_REQUEST['do'] == 'test') {
		$navbit = 'Test';
		try {
			$ts3_VirtualServer->setLoadClientlistFirst(TRUE);
			
		}
		catch(Exception $e) {
			$content .= fetch_error('neo_teamspeak_error', $e->getCode(), $e->getMessage());
		}
	}
	/* page index (default) */
	if ($_REQUEST['do'] == 'index') {
		$navbit = 'Index';
		$templater = vB_Template::create('neo_ts_index');
		$content = $templater->render();
	}	
	$neots_footer = "Executed " . $ts3_VirtualServer->getAdapter()->getQueryCount() . " queries in " . $ts3_VirtualServer->getAdapter()->getQueryRuntime() . " seconds";
	$navbits = construct_navbits(array('teamspeak.php' => $vbphrase['neo_teamspeak'], $vbphrase['neo_teamspeak'] => $navbit));
	$navbar = render_navbar_template($navbits);
	$templater = vB_Template::Create('neo_teamspeak');
	$templater->register_page_templates();
	$templater->register('navbar', $navbar);
	$templater->register('pagetitle', $pagetitle);
	$templater->register('permissions', $permissions);
	$templater->register('content', $content);
	$templater->register('neots_footer', $neots_footer);
	$templater->register('neots_border', $neots_border);
	print_output($templater->render());
}
elseif(!$vbulletin->options['neots_enabled']) {
	$content = "Teamspeak Integration is not enabled";
	$navbits = construct_navbits(array('teamspeak.php' => $vbphrase['neo_teamspeak'], $vbphrase['neo_teamspeak'] => $navbit));
	$navbar = render_navbar_template($navbits);
	
	$templater = vB_Template::Create('neo_teamspeak');
	$templater->register_page_templates();
	$templater->register('navbar', $navbar);
	$templater->register('pagetitle', $pagetitle);
	$templater->register('content', $content);
	$templater->register('neots_border', $neots_border);
	print_output($templater->render());
}
elseif(!isset($vbulletin->options['neots_uname'], $vbulletin->options['neots_pass'], $vbulletin->options['neots_ip'], $vbulletin->options['neots_port'], $vbulletin->options['neots_id'])) {
	$content = "You have not set up your Teamspeak Settings in ACP->Settings->Options->Neoobs - Teamspeak";
	$navbits = construct_navbits(array('teamspeak.php' => $vbphrase['neo_teamspeak'], $vbphrase['neo_teamspeak'] => $navbit));
	$navbar = render_navbar_template($navbits);
	
	$templater = vB_Template::Create('neo_teamspeak');
	$templater->register_page_templates();
	$templater->register('navbar', $navbar);
	$templater->register('pagetitle', $pagetitle);
	$templater->register('content', $content);
	$templater->register('neots_border', $neots_border);
	print_output($templater->render());
}
?>